//
//  MyPersonSettingViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/9/21.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "MyPersonSettingViewController.h"
#import "MyChangeSecrectViewController.h"
#import "MydataEditViewController.h"
@interface MyPersonSettingViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>

@property(nonatomic,strong)UITableView *tablview;

@property(nonatomic,strong)NSArray *titleArray;

@end

@implementation MyPersonSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    [self createNavagationBackBtn];
    [self createTableViewUI];
    // Do any additional setup after loading the view.
}

-(void)createNavagationBackBtn{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 6, 67, 23);
    UIImageView *backImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigator_btn_back"]];
    backImg.frame = CGRectMake(-10, 0, 22, 22);
    [backBtn addSubview:backImg];
    UILabel *backText = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, 65, 22)];
//    backText.text = @"返回";
    backText.font = [UIFont systemFontOfSize:17];
    [backText setBackgroundColor:[UIColor clearColor]];
    [backText setTextColor:[UIColor whiteColor]];
    [backBtn addSubview:backText];
    [backBtn addTarget:self action:@selector(leftBarButtonItemPressed:) forControlEvents:UIControlEventTouchUpInside];
    [backImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backBtn.mas_left).offset(-10);
        make.centerY.equalTo(backBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(22, 22));
    }];
    [backText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backImg.mas_right).offset(2);
        make.centerY.equalTo(backBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(65, 22));
    }];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    [self.navigationItem setLeftBarButtonItem:leftButton];
}
-(void)leftBarButtonItemPressed:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 初始化tablview
 */
-(void)createTableViewUI{
    self.tablview = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, 150) style:UITableViewStylePlain];
    [self.view addSubview:self.tablview];
    self.tablview.scrollEnabled = NO;
    self.tablview.delegate = self;
    self.tablview.dataSource = self;
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tablview.mas_bottom).offset(scaleTopAndBottom(20));
        make.size.mas_equalTo(CGSizeMake(WIDTH, scaleTopAndBottom(60)));
        make.centerX.mas_equalTo(self.view.mas_centerX);
    }];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn addTarget:self action:@selector(exitCurrentNumber:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.backgroundColor = [UIColor redColor];
    [backBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [view addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(view);
        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(150), scaleTopAndBottom(30)));
    }];
    backBtn.layer.cornerRadius = scaleLeftAndRight(15);
    backBtn.layer.masksToBounds = YES;
//    UIView *footerView = [[UIView alloc] init];
//    self.tablview.tableFooterView = footerView;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titleArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"CellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (indexPath.row == 1) {
            NSString *sizeM = [NSString stringWithFormat:@"%.fM",[self folderSize]];
        cell.detailTextLabel.text = sizeM;
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    if (indexPath.row == 2) {
        cell.detailTextLabel.text = [self getVersion];
        
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@",self.titleArray[indexPath.row]];
    
    cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"图层%ld",indexPath.row + 11]];
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.f;
}
//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
//    UIView *view = [[UIView alloc] init];
//    view.backgroundColor = [UIColor whiteColor];
//    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [backBtn addTarget:self action:@selector(exitCurrentNumber:) forControlEvents:UIControlEventTouchUpInside];
//    backBtn.backgroundColor = [UIColor redColor];
//    [backBtn setTitle:@"退出登录" forState:UIControlStateNormal];
//    [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [view addSubview:backBtn];
//    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.center.equalTo(view);
//        make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(150), scaleTopAndBottom(30)));
//    }];
//
//    return view;
//}
-(void)exitCurrentNumber:(UIButton *)btn{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"sessionId"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"GENDER"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"AUTOGRA"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Identity"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"HEADERICON"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"NAME"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"INTERST"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SECRECT"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"PHONE"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.navigationController popViewControllerAnimated:YES];

//    [[NSUserDefaults standardUserDefaults] synchronize];
}
//-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    return scaleTopAndBottom(60);
//}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
        {
            MyChangeSecrectViewController *changeSectVc = [[MyChangeSecrectViewController alloc] init];
            [self.navigationController pushViewController:changeSectVc animated:YES];
        }
            break;
        case 1:
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@%.f%@",@"清理缓存大小",[self folderSize],@"M"] message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alertView.tag = 401;
            alertView.delegate = self;
            [alertView show];
        }
            break;
        case 2:
        {
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/id1268570592?mt=8"]];
        }
            break;
        default:
            break;
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%ld",buttonIndex);
    if (alertView.tag == 401) {
        [self removeCache];
    }
    NSLog(@"清扫垃圾");
//    [self removeCache];
//    if (buttonIndex == 0) {
//
//    }
}
-(void)alertViewCancel:(UIAlertView *)alertView{


}
-(NSArray *)titleArray{
    if (_titleArray == nil) {
        _titleArray = @[@"修改密码",@"清理缓存",@"版本更新"];
    }
    return _titleArray;
}

//缓存大小

-(CGFloat)folderSize{
    CGFloat folderSize = 0.0f;
     NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) firstObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath]; NSLog(@"文件数：%ld",files.count);
    for(NSString *path in files)
    { NSString *filePath = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",path]];
      folderSize += [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil].fileSize;
    }
    //转换为M为单位
    CGFloat sizeM = folderSize /1024.0/1024.0;
    return sizeM;
}
- (void)removeCache{
    //===============清除缓存==============
    //获取路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)objectAtIndex:0];
    //返回路径中的文件数组
    NSArray *files = [[NSFileManager defaultManager]subpathsAtPath:cachePath];
    NSLog(@"文件数：%ld",[files count]);
    for(NSString *p in files){
        NSError *error;
        NSString *path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        if([[NSFileManager defaultManager]fileExistsAtPath:path]){
            BOOL isRemove = [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            if(isRemove) {
                UITableViewCell *cell = [self.tablview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
                NSString *sizeM = [NSString stringWithFormat:@"%.fM",[self folderSize]];
                cell.detailTextLabel.text = sizeM;
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"清理缓存成功" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                alertView.tag = 400;
//                [alertView show];
            //这里发送一个通知给外界，外界接收通知，可以做一些操作（比如UIAlertViewController）
        }
            else{
                NSLog(@"清除失败");
            }
        }
    }
}
-(NSString *)getVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    CFShow((__bridge CFTypeRef)(infoDictionary));
   NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
